package com.example.springdemo.controller;

import com.example.springdemo.dao.TacoRepository;
import com.example.springdemo.entity.Taco;
import com.example.springdemo.hateoas.TacoResource;
import com.example.springdemo.hateoas.TacoResourceAssembler;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.hateoas.Resources;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.util.List;

@RepositoryRestController
public class RecentTacosController {
    @Resource
    private TacoRepository tacoRepository;

    @GetMapping(path = "/tacos/recent",produces = "application/hal+json")
    public ResponseEntity<Resources<TacoResource>> recentTacos(){
        PageRequest page = PageRequest.of(0,12, Sort.by("createdAt").descending());
        List<Taco> tacos = tacoRepository.findAll(page).getContent();
        List<TacoResource> tacoResources = new TacoResourceAssembler().toResources(tacos);
        Resources<TacoResource> resourceResources = new Resources<>(tacoResources);
        resourceResources.add(ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(RecentTacosController.class).recentTacos()).withRel("recents"));
        return new ResponseEntity<>(resourceResources, HttpStatus.OK);
    }

}
